package controllers

import (
	"github.com/goravel/framework/contracts/http"
	"github.com/goravel/framework/facades"
	httpfacade "github.com/hulutech-web/http_result"

	"goravel/app/services/upload"
)

type UploadController struct {
	//Dependent services
}

func NewUploadController() *UploadController {
	return &UploadController{
		//Inject services
	}
}

// Upload 文件上传.
// @Summary file upload
// @Description 文件上传.
// @Tags UploadController
// @Security BearerAuth
// @Accept multipart/form-data
// @Produce json
// @Param file formData file true "文件"
// @Id UploadUpload
// @Param Authorization header string true "Bearer token"
// @Success 200 {object} common.SuccessResponse "Successfully retrieved Menus ."
// @Failure 500 {object} common.ErrorResponse "Internal server error."
// @OperationID Update
// @Router /api/admin/upload [post]
func (r *UploadController) Upload(ctx http.Context) http.Response {
	file, err := ctx.Request().File("file")
	if err != nil {
		return httpfacade.NewResult(ctx).Error(500, "", err.Error())
	}
	if att, err := upload.NewUploadService().Upload(ctx, file); err != nil {
		return httpfacade.NewResult(ctx).Error(500, "", err.Error())
	} else {
		return ctx.Response().Success().Json(http.Json{
			"message": "上传成功",
			"data":    att.Path,
		})
	}
}
func (r *UploadController) Wangeditor(ctx http.Context) http.Response {
	file, err := ctx.Request().File("wangeditor-uploaded-image")
	if err != nil {
		ctx.Request().AbortWithStatus(500)
		return nil
	}
	if att, err := upload.NewUploadService().Upload(ctx, file); err != nil {
		return ctx.Response().Success().Json(http.Json{
			"errno":   1, // 只要不等于 0 就行
			"message": "失败信息",
		})
	} else {
		//获取当前host
		host := facades.Config().GetString("APP_URL")
		return ctx.Response().Success().Json(http.Json{
			"errno": 0,
			"data": map[string]string{
				"url": host + "/upload/" + att.Path,
			},
		})
	}
}
